package com.atguigu.gmall.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.BaseAppV2;
import com.atguigu.gmall.realtime.bean.VisitorStats;
import com.atguigu.gmall.realtime.common.Constant;
import com.atguigu.gmall.realtime.util.AtguiguUtil;
import com.atguigu.gmall.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.Map;

import static com.atguigu.gmall.realtime.common.Constant.*;

/**
 * @Author lzc
 * @Date 2022/4/22 16:02
 */
public class VisitorStatsApp extends BaseAppV2 {
    public static void main(String[] args) {
        new VisitorStatsApp().init("VisitorStatsApp",
                                   4001,
                                   1,
                                   "VisitorStatsApp",
                                   "VisitorStatsApp",
                                   TOPIC_DWD_PAGE, TOPIC_DWM_UV, TOPIC_DWM_UJ
        );
    }
    
    @Override
    public void handle(StreamExecutionEnvironment env,
                       Map<String, DataStreamSource<String>> topicToStreamMap) {
        /*topicToStreamMap.get(TOPIC_DWD_PAGE).print(TOPIC_DWD_PAGE);
        topicToStreamMap.get(TOPIC_DWM_UV).print(TOPIC_DWM_UV);
        topicToStreamMap.get(TOPIC_DWM_UJ).print(TOPIC_DWM_UJ);*/
        
        // 1. 把多个流union成一个流
        DataStream<VisitorStats> visitorStatsDataStream = unionOneStream(topicToStreamMap);
        // 2. 开窗聚合
        SingleOutputStreamOperator<VisitorStats> aggregatedVisitorStatsStream = windowAndAgg(visitorStatsDataStream);
        // 3. 把结果写入到clickhouse中
        writeToClickHouse(aggregatedVisitorStatsStream);
        
        
    }
    
    private void writeToClickHouse(SingleOutputStreamOperator<VisitorStats> aggregatedVisitorStatsStream) {
        aggregatedVisitorStatsStream.addSink(FlinkSinkUtil.getClickHouseSink(Constant.CLICKHOUSE_DB, "visitor_stats_2022", VisitorStats.class));
    }
    
    private SingleOutputStreamOperator<VisitorStats> windowAndAgg(DataStream<VisitorStats> visitorStatsDataStream) {
        /*
        1. sum max min maxBy minBy
        2. reduce
        3. aggregate
        4. process
        
         */
        return visitorStatsDataStream
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<VisitorStats>forBoundedOutOfOrderness(Duration.ofSeconds(10))
                    .withTimestampAssigner((vs, ts) -> vs.getTs())
                    .withIdleness(Duration.ofSeconds(10))  // 如果某个并行度的数据不更新, 导致水印不更新. 超过10s不更新, 以其他并行度的水印为准
            
            )
            .keyBy(vs -> vs.getCh() + "_" + vs.getVc() + "_" + vs.getAr() + "_" + vs.getIs_new())
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .sideOutputLateData(new OutputTag<VisitorStats>("late") {})
            .reduce(
                new ReduceFunction<VisitorStats>() {
                    @Override
                    public VisitorStats reduce(VisitorStats vs1,
                                               VisitorStats vs2) throws Exception {
                        vs1.setUv_ct(vs1.getUv_ct() + vs2.getUv_ct());
                        vs1.setPv_ct(vs1.getPv_ct() + vs2.getPv_ct());
                        vs1.setSv_ct(vs1.getSv_ct() + vs2.getSv_ct());
                        vs1.setUj_ct(vs1.getUj_ct() + vs2.getUj_ct());
                        vs1.setDur_sum(vs1.getDur_sum() + vs2.getDur_sum());
                        
                        return vs1;
                    }
                },
                new ProcessWindowFunction<VisitorStats, VisitorStats, String, TimeWindow>() {
                    @Override
                    public void process(String key,
                                        Context ctx,
                                        Iterable<VisitorStats> elements,  // 有且仅有一个值, 聚合的最终结果
                                        Collector<VisitorStats> out) throws Exception {
                        String stt = AtguiguUtil.toDateTime(ctx.window().getStart());
                        String edt = AtguiguUtil.toDateTime(ctx.window().getEnd());
                        
                        
                        VisitorStats vs = elements.iterator().next();
                        vs.setStt(stt);
                        vs.setEdt(edt);
                        out.collect(vs);
                        
                        // 把ts改成统计时间
                        vs.setTs(System.currentTimeMillis());
                        
                    }
                }
            );
    }
    
    private DataStream<VisitorStats> unionOneStream(Map<String, DataStreamSource<String>> topicToStreamMap) {
        // 1. pv 和持续访问时间
        SingleOutputStreamOperator<VisitorStats> pvAndDuringTimeStream = topicToStreamMap
            .get(TOPIC_DWD_PAGE)
            .map(json -> {
                JSONObject obj = JSON.parseObject(json);
                
                JSONObject common = obj.getJSONObject("common");
                
                String vc = common.getString("vc");
                String ch = common.getString("ch");
                String ar = common.getString("ar");
                String is_new = common.getString("is_new");
                
                Long during_time = obj.getJSONObject("page").getLong("during_time");
                
                Long ts = obj.getLong("ts");
                
                
                return new VisitorStats("", "",
                                        vc, ch, ar, is_new,
                                        0L, 1L, 0L, 0L, during_time,
                                        ts
                );
                
                
            });
        
        // 2. uv
        SingleOutputStreamOperator<VisitorStats> uvStream = topicToStreamMap
            .get(TOPIC_DWM_UV)
            .map(json -> {
                JSONObject obj = JSON.parseObject(json);
                
                JSONObject common = obj.getJSONObject("common");
                
                String vc = common.getString("vc");
                String ch = common.getString("ch");
                String ar = common.getString("ar");
                String is_new = common.getString("is_new");
                
                
                Long ts = obj.getLong("ts");
                
                
                return new VisitorStats("", "",
                                        vc, ch, ar, is_new,
                                        1L, 0L, 0L, 0L, 0L,
                                        ts
                );
                
                
            });
        
        
        // 3. uj
        SingleOutputStreamOperator<VisitorStats> ujStream = topicToStreamMap
            .get(TOPIC_DWM_UJ)
            .map(json -> {
                JSONObject obj = JSON.parseObject(json);
                
                JSONObject common = obj.getJSONObject("common");
                
                String vc = common.getString("vc");
                String ch = common.getString("ch");
                String ar = common.getString("ar");
                String is_new = common.getString("is_new");
                
                
                Long ts = obj.getLong("ts");
                
                
                return new VisitorStats("", "",
                                        vc, ch, ar, is_new,
                                        0L, 0L, 0L, 1L, 0L,
                                        ts
                );
                
                
            });
        
        // 3. uj
        SingleOutputStreamOperator<VisitorStats> svStream = topicToStreamMap
            .get(TOPIC_DWD_PAGE)
            .flatMap(new FlatMapFunction<String, VisitorStats>() {
                @Override
                public void flatMap(String json,
                                    Collector<VisitorStats> out) throws Exception {
                    JSONObject obj = JSON.parseObject(json);
                    
                    String lastPageId = obj.getJSONObject("page").getString("last_page_id");
                    
                    if (lastPageId == null || lastPageId.length() == 0) {
                        JSONObject common = obj.getJSONObject("common");
                        
                        String vc = common.getString("vc");
                        String ch = common.getString("ch");
                        String ar = common.getString("ar");
                        String is_new = common.getString("is_new");
                        
                        
                        Long ts = obj.getLong("ts");
                        VisitorStats vs = new VisitorStats("", "",
                                                           vc, ch, ar, is_new,
                                                           0L, 0L, 1L, 0L, 0L,
                                                           ts
                        );
                        out.collect(vs);
                        
                    }
                    
                    
                }
            });
        
        
        return pvAndDuringTimeStream.union(uvStream, ujStream, svStream);
        
        
    }
}
/*
dwd_page
ar  pv    uv   uj
..   1     0   0

dwm_uv
ar  pv    uv   uj
..   0     1   0

dwm_uj
ar  pv    uv   uj
..   0    0     1

--------------

union

--------------------
ar      pv   uv   uj
...    1    0   0
...    1    0   0
...    0    1   0
开窗聚合
--------------
最终
窗口  ar      pv   uv   uj
0-5  ...     20    11   15
5-10  ...    22    12   16

 */